package nio.cp3_channel;

import com.sun.corba.se.spi.orbutil.threadpool.Work;

import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Random;

public class PipeTest {

    public static void main(String[] args) throws Exception {

        WritableByteChannel out = Channels.newChannel(System.out);

        ReadableByteChannel readableByteChannel = startWorker(10);
        ByteBuffer buffer = ByteBuffer.allocate(100);
        while (readableByteChannel.read(buffer) > 0) {
            buffer.flip();
            out.write(buffer);
            buffer.clear();
        }
    }
    private static ReadableByteChannel startWorker (int reps)
            throws Exception
    {
        Pipe pipe = Pipe.open();
        Worker worker = new Worker(pipe.sink(), reps);
        new Thread(worker).start();

        return pipe.source();

    }
    public static class Worker implements Runnable{

        WritableByteChannel channel;
        private int reps;
        private String [] products = {
                "No good deed goes unpunished",
                "To be, or what?",
                "No matter where you go, there you are",

                "Just say \"Yo\"",
                "My karma ran over my dogma"
        };
        private Random rand = new Random( );

        private void doSomeWork (ByteBuffer buffer)
        {
            int product = rand.nextInt (products.length);
            buffer.clear();
            buffer.put(products[product].getBytes());
            buffer.put ("\r\n".getBytes( ));
            buffer.flip();
        }


        Worker (WritableByteChannel channel, int reps){
            this.channel = channel;
            this.reps = reps;
        }

        @Override
        public void run() {

            ByteBuffer buffer = ByteBuffer.allocate(100);
            for (int i = 0; i < reps; i++) {

                doSomeWork(buffer);
                try {
                    while (channel.write(buffer) > 0) {
                        System.out.println("111111");
                    }
                } catch (Exception e) {

                }

            }

        }
    }
}
